<template>
  <base-breadcrumb :title="$route.meta.title">
    <!-- 租赁房产管理编辑 -->

    <a-spin :spinning="loading">
      <div>
        <!-- 表单 -->
        <a-card :bordered="false">
          <title-name title="基本信息" />
          <a-form-model
            ref="ruleForm"
            :model="form"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
            :rules="editModel != 0 ? rules : {}"
          >
            <custom-form
              :form-list="formList"
              :form="form"
              :edit-model="editModel == 0 ? '' : ''"
            />
          </a-form-model>
        </a-card>
        <a-card :bordered="false">
          <!-- 门牌号信息 -->
          <title-name title="门牌号信息" />
          <a-row :gutter="24">
            <a-col
              :md="24"
              :sm="24"
            >
              <div class="flex-row mb20">
                <a-button
                  :disabled="editModel == 0"
                  class="ml20"
                  type="primary"
                  @click="addLine()"
                >
                  添加行
                </a-button>
              </div>
              <s-table
                ref="table"
                bordered
                size="default"
                row-key="key"
                :columns="columns"
                :data="loadData"
                :is-delete="true"
                :alert="true"
                show-size-changer
                show-quick-jumper
                :show-pagination="false"
              >
                <template
                  slot="houseNum"
                  slot-scope="text, record"
                >
                  <BaseInput
                    v-if="record.editable"
                    :value="text"
                    placeholder="请输入"
                    @change="(e) => handleChange(e.target.value, record.key, 'houseNum')"
                  />
                  <span v-else>{{ text }}</span>
                </template>
                <template
                  slot="builtArea"
                  slot-scope="text, record"
                >
                  <BaseInput
                    v-if="record.editable"
                    :value="text"
                    :max-length="100"
                    placeholder="请输入"
                    @change="(e) => handleChange(e.target.value, record.key, 'builtArea')"
                  />
                  <span v-else>{{ text }} </span>
                </template>

                <template
                  slot="residents"
                  slot-scope="text, record"
                >
                  <a-tag
                    v-for="(person, index) in record.residents"
                    :key="person.id || person"
                    class="mb20"
                    :closable="record.editable"
                    color="#108ee9"
                    @close="() => handleClosePerson(record, index)"
                  >
                    {{ person.name || person }}
                  </a-tag>
                  <a
                    v-if="record.editable"
                    @click="() => handleChangePerson(record)"
                  >添加入住人</a>
                </template>
                <template
                  slot="action"
                  slot-scope="text, record, index"
                >
                  <span v-if="record.editable">
                    <a @click="() => save(record)">保存</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确定要取消保存?"
                      @confirm="() => cancel(record.key, index)"
                    >
                      <a>取消</a>
                    </a-popconfirm>
                  </span>
                  <span v-else>
                    <a
                      :disabled="editingKey !== '' || editModel == 0"
                      @click="() => edit(record.key)"
                    >编辑</a>
                    <a-divider type="vertical" />
                    <a-popconfirm
                      title="确定要删除?"
                      @confirm="() => del(record, index)"
                    >
                      <a :disabled="editingKey !== '' || editModel == 0">删除</a>
                    </a-popconfirm>
                  </span>
                </template>
              </s-table>
            </a-col>
          </a-row>
        </a-card>
      </div>
    </a-spin>
    <!-- 编辑入住人 -->
    <updatePerson
      ref="updatePerson"
      :persons="modelData.residents"
      :visible.sync="visible"
      @confirm="submitForm"
    />
    <!-- 页脚操作栏 -->

    <div class="tool-btns page-btn-right-top">
      <a-button
        v-if="editModel != 0"
        :loading="loading"
        type="primary"
        class="button_right"
        @click="handleSubmit"
      >
        提交
      </a-button>
      <a-button
        class="ml20"
        type="primary"
        @click="handleClose"
      >
        关闭
      </a-button>
    </div>
  </base-breadcrumb>
</template>

<script>
import { getDormitory, addDormitory } from '@/api/office/propertyManagement' // api
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import TreeSelectOrganization from '@/components/TreeSelectOrganization'
import Selector from '@/components/Select/Selector'
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import { STable } from '@/components' // 表格
import updatePerson from './updatePerson' // 编辑入住人
const columns = [
  {
    title: '序号',
    width: 80,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '*门牌号',
    dataIndex: 'houseNum',
    scopedSlots: { customRender: 'houseNum' },
    width: '20%'
  },

  {
    title: '面积',
    dataIndex: 'builtArea',
    scopedSlots: { customRender: 'builtArea' },
    width: '20%'
  },
  {
    title: '入住人',
    dataIndex: 'residents',
    scopedSlots: { customRender: 'residents' },
    width: '45%'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' }
  }
]
export default {
  extends: new BaseEditPage(),
  components: {
    STable,
    updatePerson
  },
  data() {
    this.columns = columns
    return {
      childInitData: {},
      visible: false,
      loading: false, // 加载控件
      editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
      form: { orgDeptName: '', orgDeptId: '', houseUseId: '697698462820601857', list: [] }, // 表单
      rules: {
        totalArea: [{ required: true, message: '建筑面积(m²)', trigger: 'change' }]
      }, // 校验规则
      init: false, // 初始化控件
      formCode: '', // 形式选中项code
      key: 0,
      cacheData: {},
      modelData: {},
      editingKey: '',
      persons: [], //当前行入住人
      loadData: () => {
        if (this.form.list?.length) {
          return new Promise((resolve, reject) => {
            resolve({
              data: this.form.list
            })
          })
        }
      }
    }
  },

  mounted() {
    let userInfo = JSON.parse(sessionStorage.getItem('ycloud-user_info'))

    this.form.orgDeptName = (userInfo.currentPost.code === 'PD' ? userInfo.currentPost.orgName + '-' : '') + userInfo.currentPost.name
    this.form.orgDeptId = userInfo.currentPost.id

    this.$route.meta.title = ['租赁房产管理查看', '租赁房产管理编辑', '租赁房产管理新增'][this.editModel]
    // 不为添加时请求详情
    if (this.editModel != 2) {
      this.loading = true
      getDormitory(this.id)
        .then((res) => {
          this.loading = false

          this.form = res.data
          console.log(res.data)
          this.form.list = []
          this.form.list.push({
            houseNum: this.form.houseNum,
            builtArea: this.form.builtArea,
            residents: this.form.residentsUser.split(',')
          })
          console.log(this.form)
          this.$refs.table.refresh(true)
          this.$nextTick(() => {
            this.init = true
          })
        })
        .catch(() => {
          this.loading = false
        })
    } else {
      this.$nextTick(() => {
        this.init = true
      })
    }
  },
  computed: {
    formList() {
      return [
        {
          keyName: 'orgDeptName',
          type: TreeSelectOrganization,
          label: '单位',
          disabled: true,
          attrs: {
            orgQuery: {
              containTags: ['CO', 'BC', 'PD'],
              resultWithCODept: true,
              resultWithBCDept: true,
              resultWithPDDept: true
            },
            containVirtual: true
          }
        },
        {
          keyName: 'totalArea',
          type: 'BaseInputNumber',
          disabled: this.editModel == 0,
          label: '建筑面积(m²)'
        },
        {
          keyName: 'houseUseId',
          disabled: true,
          label: '房屋用途',
          type: Selector,
          attrs: {
            selectType: '3',
            urlType: 'office'
          }
        }
      ]
    }
  },
  methods: {
    submitForm(e) {
      this.modelData.residents = e

      this.form.list.forEach((item, index) => {
        if (item.key == this.modelData.key) {
          this.form.list[index] = this.modelData
        }
      })

      console.log(this.form)
      this.$refs.table.refresh(true)
    },
    handleClosePerson(record, index) {
      record.residents.splice(index, 1)
    },
    handleChange(value, key, column) {
      const newData = [...this.form.list]
      const target = newData.filter((item) => key === item.key)[0]
      if (target) {
        target[column] = value
        this.form.list = newData
      }
    },
    handleChangePerson(record) {
      this.cacheData = this.$clone(record)
      this.modelData = this.$clone(record)
      this.visible = true
    },
    del(data, idx) {
      this.form.list.splice(idx, 1)
      this.$refs.table.refresh(true)
    },
    edit(key) {
      const newData = [...this.form.list]
      const target = newData.filter((item) => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.form.list = newData
      }
      this.cacheData = this.$clone(target)
      this.$refs.table.refresh(true)
    },
    async save(data) {
      if (data.houseNum == '') {
        this.$message.warning('请输入门牌号')
        return
      }
      data.editable = false
      data.isAdd = false
      this.cacheData = {}
      this.editingKey = ''
    },
    cancel(key, index) {
      console.log(this.cacheData)

      this.form.list.forEach((item, index) => {
        console.log(item.key)
        console.log(this.cacheData.key)
        if (item.key == this.cacheData.key) {
          console.log('sda')
          this.form.list[index] = this.cacheData
          this.form.list[index].editable = false
          if (item.isAdd) {
            this.form.list.splice(index, 1)
          }
        }
      })
      console.log(this.form.list)
      this.editingKey = ''
      this.$refs.table.refresh(true)
    },
    addLine() {
      this.form.list.push({
        key: this.key,
        houseNum: '',
        builtArea: '',
        residents: [],
        editable: true,
        isAdd: true //第一次新增，用于点击取消时删除此项
      })
      this.key++
      console.log(this.form.list)
      this.cacheData = this.form.list[this.form.list.length - 1]
      this.$refs.table.refresh(true)
    },
    formatData() {
      let data = []
      this.form.list.forEach((item) => {
        let residents = []
        item.residents.forEach((item) => {
          residents.push(item.userId)
        })
        data.push({
          builtArea: item.builtArea,
          houseNum: item.houseNum,
          houseUseId: this.form.houseUseId,
          orgDeptId: this.form.orgDeptId,
          orgDeptName: this.form.orgDeptName,
          residents: residents,
          totalArea: this.form.totalArea
        })
      })
      return data
    },
    /**
     * 提交表单
     */
    handleSubmit() {
      let that = this
      // let api = [update, addDormitory][that.editModel - 1] // 根据操作切换url地址
      // 校验表单
      that.$refs.ruleForm.validate((e) => {
        if (e) {
          // 提交表单
          that.loading = true
          let params = this.formatData()
          addDormitory(params)
            .then(() => {
              that.loading = false
              that.$message.success('提交成功！')
              that.$multiTab.close()
            })
            .catch(() => {
              that.loading = false
            })
        }
      })
    },
    handleClose() {
      if (this.isAudit) {
        window.close()
      } else {
        this.$multiTab.close(this.$route.fullpath)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.file_prompt {
  color: #999;
}
</style>